package xcmg.device.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class CommonUtils {

    public static Random random = new Random();

    private final static String WAREHOUSE_CODE_SEPARATOR = "-";

    private CommonUtils() {
    }

    public static void setHttpResponse(HttpServletResponse response, String title) throws UnsupportedEncodingException {
        Format format = new SimpleDateFormat("yyyyMMdd");
        String fileName = "Excel-" + format.format(new Date()) + title;
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xlsx");
        response.setContentType("application/x-msdownload");
    }

    public static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String generateString(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 根据库区编码获取仓库编码
     *
     * @param code
     * @return
     */
    public static String getCodeByAreaCode(String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        //AreaCode格式:仓库01-库区01
        String[] codes = code.split(WAREHOUSE_CODE_SEPARATOR);
        if ((codes.length - 1) < 0) {
            return "";
        }
        return codes[1];
    }

    /**
     * 提取仓库编号
     *
     * @param code
     * @return
     */
    public static String getWarehouseCode(String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        String[] codes = code.split(WAREHOUSE_CODE_SEPARATOR);
        if (codes.length < 2) {
            return "";
        }
        return codes[codes.length - 1];
    }

    /**
     * 提取库区编号
     *
     * @param code
     * @return
     */
    public static String getWarehouseAreaCode(String code) {
        if (StringUtils.isBlank(code)) {
            return "";
        }
        //LocationCode格式:储位01-1-1-1-1-库区01-仓库01
        String[] codes = code.split(WAREHOUSE_CODE_SEPARATOR);
        if (codes.length < 2) {
            return "";
        }
        return codes[codes.length - 2];
    }

    public static Integer tryParseInt(String s) {
        if (!isNumber(s)) {
            return null;
        }
        try {
            BigDecimal bigDecimal = new BigDecimal(s).setScale(0, BigDecimal.ROUND_DOWN);
            return Integer.parseInt(bigDecimal.toString());
        } catch (Exception e) {
            return null;
        }
    }

    public static Integer tryParseInt(String s, int defaultValue) {
        if (!isNumber(s)) {
            return defaultValue;
        }
        try {
            BigDecimal bigDecimal = new BigDecimal(s).setScale(0, BigDecimal.ROUND_DOWN);
            return Integer.parseInt(bigDecimal.toString());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Long tryParseLong(String s, Long defaultValue) {
        if (!isNumber(s)) {
            return defaultValue;
        }
        try {
            return Long.valueOf(s);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Long tryParseLongWithError(String s, String msg) {
        if (!isNumber(s)) {
            throw new RuntimeException(msg);
        }
        try {
            return Long.valueOf(s);
        } catch (Exception e) {
            throw new RuntimeException(msg);
        }
    }

    public static boolean validateIntegerInCollection(Integer i, Collection<Integer> c) {
        if (CollectionUtils.isEmpty(c) || null == i) {
            return false;
        }
        Set<Integer> s = new HashSet<>(c);
        return s.contains(i);
    }

    private static boolean isNumber(String str) {
        if (str == null) {
            return false;
        }
        String reg = "-?[0-9]+.?[0-9]+";
        String regAct = "^-?\\d+(\\.\\d+)?(E-?\\d+)?$";
        return str.matches(reg) || str.matches(regAct);
    }

    public static String getEnglishPrefix(String input) {
        // 匹配开头的连续英文字母（直到遇到数字或字符串结束）
        java.util.regex.Matcher matcher = java.util.regex.Pattern.compile("^[a-zA-Z]+").matcher(input);
        return matcher.find() ? matcher.group() : "";
    }
}
